<template>
  <div class="login-container">
    <div class="title-container">
      <div class="logo">
        <img
          alt="logo"
          class="antd-pro-layouts-user-layout-logo"
          :src="imgLogo"
        >
      </div>
      <div class="name">
        <h3 class="title">CicadasCMS v2.0</h3>
      </div>
    </div>
    <div class="tips">一个人不要太优秀，相当优秀就可以了。</div>
    <el-tabs v-model="activeName" class="login-form" @tab-click="handleClick">
      <el-tab-pane label="帐号密码登陆" name="first">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          auto-complete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-col :span="15">
            <el-form-item class="verify-image-item" prop="imageCode">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                ref="imageCode"
                v-model="loginForm.imageCode"
                placeholder="验证码"
                name="imageCode"
                type="text"
                tabindex="3"
                auto-complete="on"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9" style="padding-left:5px">
            <img style="width:100%;height:41px;" :src="imageCodeState.imgSrc" @click="getImageCode">
          </el-col>
          <el-button
            :loading="loading"
            type="primary"
            style="width:100%;margin-bottom:30px;"
            @click.native.prevent="handleLogin"
          >登陆</el-button>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="手机号登陆" name="second">
        <el-form
          ref="mobileLoginForm"
          :model="mobileLoginForm"
          :rules="mobileLoginRules"
          auto-complete="on"
          label-position="left"
        >
          <el-form-item prop="mobile">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="mobile"
              v-model="mobileLoginForm.mobile"
              placeholder="手机号"
              name="mobile"
              type="number"
              tabindex="4"
              auto-complete="on"
            />
          </el-form-item>
          <el-col :span="15">
            <el-form-item class="verify-image-item" prop="smsCode">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
              <el-input
                ref="smsCode"
                v-model="mobileLoginForm.smsCode"
                placeholder="短信验证码"
                name="smsCode"
                type="text"
                tabindex="5"
                auto-complete="on"
              />
            </el-form-item>
          </el-col>
          <el-col :span="9" style="padding-left:5px">
            <el-button
              :disabled="smsCodeState.btnDisable"
              style="width:100%;height:42.5px"
              @click="getSmsCode()"
            >{{ smsCodeState.btnName }}</el-button>
          </el-col>
          <el-button
            :loading="loading"
            type="primary"
            style="width:100%;margin-bottom:30px;"
            @click.native.prevent="handleMobileLogin"
          >登陆</el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <div class="company_info">&copy; CicadasCMS 2017-2020 </div>
    </div>
  </div>
</template>

<script>
import { validMobile } from '@/utils/validate'
import { getCaptch, getSmsDeviceId, sendSmsCode } from '@/api/user'
import { Message } from 'element-ui'
// import { log } from 'util'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error('请输入正确手机号'))
      } else {
        callback()
      }
    }
    const validateImageCode = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    const validateSmsCode = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入短信验证码'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        imageCode: '',
        deviceId: undefined
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        imageCode: [
          { required: true, trigger: 'blur', validator: validateImageCode }
        ]
      },
      mobileLoginForm: {
        mobile: '',
        smsCode: '',
        deviceId: undefined
      },
      mobileLoginRules: {
        mobile: [
          { required: true, trigger: 'blur', validator: validateMobile }
        ],
        smsCode: [
          { required: true, trigger: 'blur', validator: validateSmsCode }
        ]
      },
      imgLogo:'',
      smsCodeState: {
        timer: 60,
        btnName: '获取验证码',
        btnDisable: false
      },
      imageCodeState: {
        imgSrc: ''
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      activeName: 'first'
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted: function() {
    const that = this
    this.getImageCode()
    getSmsDeviceId()
      .then(response => {
        const { data } = response
        that.mobileLoginForm.deviceId = data
      })
      .catch(error => {
        console.error(error)
      })
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab)
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 获取图片验证码
    getImageCode() {
      getCaptch()
        .then(response => {
          const { data } = response
          this.imageCodeState.imgSrc = data.base64Image
          this.loginForm.deviceId = data.deviceId
        })
        .catch(error => {
          console.error(error)
          Message({
            message: '获取图片验证码失败！',
            type: 'error',
            duration: 3 * 1000
          })
        })
    },
    getSmsCode() {
      const me = this
      if (validMobile(me.mobileLoginForm.mobile)) {
        let sendSuccessed = false
        sendSmsCode(this.mobileLoginForm).then(response => {
          const { code, data } = response
          if (code === 20000) {
            Message({
              message: data,
              type: 'success',
              duration: 3 * 1000
            })
            sendSuccessed = true
            me.smsCodeState.btnDisable = true
            me.smsCodeState.timer = 60
            me.smsCodeState.btnName = '短信发送中'
            const myTime = setInterval(() => {
              if (me.smsCodeState.btnDisable) {
                const t = (me.smsCodeState.timer = me.smsCodeState.timer - 1)
                const msg = '短信发送中(' + t + ')'
                me.smsCodeState.btnName = msg
                if (t < 1) {
                  me.smsCodeState.btnDisable = false
                  me.smsCodeState.btnName = '重新获取验证码'
                  clearInterval(myTime)
                }
              }
            }, 1000)
          } else {
            Message({
              message: data,
              type: 'error',
              duration: 3 * 1000
            })
          }
        })
      } else {
        this.$nextTick(() => {
          this.$refs.mobile.focus()
        })
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 登录按钮
    handleMobileLogin() {
      const that = this
      this.$refs.mobileLoginForm.validate(valid => {
        if (valid) {
          that.loading = true
          that.$store
            .dispatch('user/loginByMobile', that.mobileLoginForm)
            .then(() => {

              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #fff;
$light_gray: #000;
$cursor: rgb(7, 6, 6);

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 30px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 40px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid #d9d9d9;
    background: #fff;
    border-radius: 5px;
    color: #d9d9d9;
  }

  .el-tabs__nav-wrap::after {
    background: #f4f4f5;
  }
  .el-tabs__nav-scroll {
    text-align: center;
    margin-bottom: 20px;
  }
  .el-tabs__header {
    margin-left: 25%;
  }
  .el-form-item__content {
    line-height: 25px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #f4f4f5;
$bgImg: "../../assets/login_images/login-bg.svg";
$dark_gray: #889aa4;
$light_gray: #000;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  text-align: center;
  background-image: url($bgImg);
  background-repeat: no-repeat;
  background-size: 100%;
  position: relative;
  .login-form {
    position: relative;
    width: 500px;
    max-width: 100%;
    padding: 5px 35px 0;
    margin: 0 auto;
    overflow: hidden;
    text-align: center;
  }
  .verify-image-item {
    padding-left: 10px;
  }
  .tips {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.45);
    margin-bottom: 30px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 50px;
    height: auto;
    .logo {
      display: inline-block;
      width: 44px;
      margin-right: 10px;
      img {
        width: 44px;
      }
    }
    .name {
      display: inline-block;
      width: auto;
      .title {
        font-size: 26px;
        color: #000;
        text-align: center;
        font-weight: bold;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .verifyCode {
    width: 40px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    margin: 0 0 20px 0;
    text-align: center;
    padding: 0 16px;
    .company_info {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.45);
    }
  }
}
</style>
